package com.android.dialnowsms;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;

public class Phone2PhoneCaller implements Runnable, OnClickListener 
{
	private String url;
	private String response;
	private String phone_number;
	private String error_message;
	private String service_url;
	private String username;
	private String password;
	private String sender_number;
	private String country_prefix;
	private SMSComposer composer_view;
	
	
	public Phone2PhoneCaller(SMSComposer smsComposer)
	{
		composer_view = smsComposer;
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(composer_view);
		username = prefs.getString("username", "");
		password = prefs.getString("password", "");
		service_url = prefs.getString("service_url", "dialnow.com");
		sender_number = prefs.getString("sender_number", "");
		country_prefix = prefs.getString("country_prefix", "");
	}
	
	//@Override
	public void onClick(View v) 
	{
	    Thread thread = new Thread(this);
	    thread.start();
	    composer_view.log.setText("sending message...");
	    composer_view.progress.setVisibility(View.VISIBLE);
	  }
	
	//@Override
	public void run() 
	{
		HttpClient httpClient = new DefaultHttpClient();

	    phone_number = composer_view.number.getText() + "";
	    
	    
	    if (phone_number.startsWith("00")) 
	    {
	    	// Phone number is like 0041791234123...
	    	phone_number = "+" + (composer_view.number.getText() + "").substring(2);
	    } 
	    else if (phone_number.startsWith("0")) 
	    {
	    	// Phone number is like 0791231211...
	    	phone_number = country_prefix + (composer_view.number.getText() + "").substring(1);
	    
	    }
	    else if  (! phone_number.startsWith("+") && !"".equals(country_prefix)) 
	    {
	    	// Phone number is like 791231211...
	    	phone_number = country_prefix + composer_view.number.getText();
	    }
	    
	    url = "https://www." + service_url
	    + "/myaccount/makecall.php?" 
	    + "username=" + username + "&password=" + password
	    + "&from=" + sender_number + "&to=" + phone_number;
	    
	    try 
	    {
	    	HttpGet httpGet = new HttpGet(url);
	        ResponseHandler<String> rh = new BasicResponseHandler();
	        response = httpClient.execute(httpGet, rh);
	    } 
	    catch (ClientProtocolException e) 
	    {
	        error_message = "error sending message ClientProtocolException";
	    }
	    catch (IOException e) 
	    {
	    	error_message = "error sending message IOException";
	    }
	    handler.sendEmptyMessage(0);

	}
	
	 private Handler handler = new Handler() 
	 {
		 @Override
		 public void handleMessage(Message msg) 
		 {
			 composer_view.progress.setVisibility(View.GONE);

			 if (error_message != null) 
			 {
				 composer_view.log.setText(error_message);
			 }
			 else 
			 {
				 response = response.replace("\n", " ");
				 Boolean success = response.indexOf("success") > 0;
				 if (success) 
				 {
					 composer_view.log.setText("Phone 2 Phone started with " + phone_number);
				 }
				 else 
				 {
					 String error_msg = "There was an error initating a call:\n";
					 error_msg += "Service URL used: " + service_url + "\n";
					 error_msg += "Username used: " + username + "\n";
					 error_msg += "Caller number: " + sender_number + "\n";
					 error_msg += "Destination number: " + phone_number + "\n";					 
					 error_msg += "Error: ";
					 
					 Pattern pattern = Pattern.compile("<description>(.*?)</description>");
					 Matcher matcher = pattern.matcher(response);
					 if (matcher.find()) 
					 {
						 composer_view.log.setText(error_msg + matcher.group(1));
					 }
				 }
			 }
		 }
	};
}
